package com.kkkkkba.search.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.kkkkkba.search.model.entity.Code;
import com.kkkkkba.search.model.vo.CodeVO;
import com.kkkkkba.search.annotation.AuthCheck;
import com.kkkkkba.search.common.BaseResponse;
import com.kkkkkba.search.common.DeleteRequest;
import com.kkkkkba.search.common.ErrorCode;
import com.kkkkkba.search.common.ResultUtils;
import com.kkkkkba.search.constant.UserConstant;
import com.kkkkkba.search.exception.BusinessException;
import com.kkkkkba.search.exception.ThrowUtils;
import com.kkkkkba.search.model.dto.code.CodeAddRequest;
import com.kkkkkba.search.model.dto.code.CodeEditRequest;
import com.kkkkkba.search.model.dto.code.CodeQueryRequest;
import com.kkkkkba.search.model.dto.code.CodeUpdateRequest;
import com.kkkkkba.search.model.entity.User;
import com.kkkkkba.search.service.CodeService;
import com.kkkkkba.search.service.UserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码接口
 *

 */
@RestController
@RequestMapping("/code")
@Slf4j
@Api(tags = "代码接口")
public class CodeController {

    @Resource
    private CodeService codeService;

    @Resource
    private UserService userService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param codeAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addCode(@RequestBody CodeAddRequest codeAddRequest, HttpServletRequest request) {
        if (codeAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Code code = new Code();
        BeanUtils.copyProperties(codeAddRequest, code);
        List<String> tags = codeAddRequest.getTags();
        if (tags != null) {
            code.setTags(GSON.toJson(tags));
        }
        codeService.validCode(code, true);
        User loginUser = userService.getLoginUser(request);
        code.setUserId(loginUser.getId());
        code.setFavourNum(0);
        code.setThumbNum(0);
        boolean result = codeService.save(code);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newCodeId = code.getId();
        return ResultUtils.success(newCodeId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteCode(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Code oldCode = codeService.getById(id);
        ThrowUtils.throwIf(oldCode == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldCode.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = codeService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param codeUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateCode(@RequestBody CodeUpdateRequest codeUpdateRequest) {
        if (codeUpdateRequest == null || codeUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Code code = new Code();
        BeanUtils.copyProperties(codeUpdateRequest, code);
        List<String> tags = codeUpdateRequest.getTags();
        if (tags != null) {
            code.setTags(GSON.toJson(tags));
        }
        // 参数校验
        codeService.validCode(code, false);
        long id = codeUpdateRequest.getId();
        // 判断是否存在
        Code oldCode = codeService.getById(id);
        ThrowUtils.throwIf(oldCode == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = codeService.updateById(code);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<CodeVO> getCodeVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Code code = codeService.getById(id);
        if (code == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(codeService.getCodeVO(code, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param codeQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<CodeVO>> listCodeVOByPage(@RequestBody CodeQueryRequest codeQueryRequest,
            HttpServletRequest request) {
        long current = codeQueryRequest.getCurrent();
        long size = codeQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<CodeVO> codePage = codeService.listCodeVOByPage(codeQueryRequest,request);
        return ResultUtils.success(codePage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param codeQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<CodeVO>> listMyCodeVOByPage(@RequestBody CodeQueryRequest codeQueryRequest,
            HttpServletRequest request) {
        if (codeQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        codeQueryRequest.setUserId(loginUser.getId());
        long current = codeQueryRequest.getCurrent();
        long size = codeQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Code> codePage = codeService.page(new Page<>(current, size),
                codeService.getQueryWrapper(codeQueryRequest));
        return ResultUtils.success(codeService.getCodeVOPage(codePage, request));
    }




    // endregion

    /**
     * 分页搜索（从 ES 查询，封装类）
     *
     * @param codeQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/search/page/vo")
    public BaseResponse<Page<CodeVO>> searchCodeVOByPage(@RequestBody CodeQueryRequest codeQueryRequest,
            HttpServletRequest request) {
        long size = codeQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<CodeVO> codePage = codeService.listCodeVOByPage(codeQueryRequest,request);
        return ResultUtils.success(codePage);
    }

    /**
     * 编辑（用户）
     *
     * @param codeEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editCode(@RequestBody CodeEditRequest codeEditRequest, HttpServletRequest request) {
        if (codeEditRequest == null || codeEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Code code = new Code();
        BeanUtils.copyProperties(codeEditRequest, code);
        List<String> tags = codeEditRequest.getTags();
        if (tags != null) {
            code.setTags(GSON.toJson(tags));
        }
        // 参数校验
        codeService.validCode(code, false);
        User loginUser = userService.getLoginUser(request);
        long id = codeEditRequest.getId();
        // 判断是否存在
        Code oldCode = codeService.getById(id);
        ThrowUtils.throwIf(oldCode == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldCode.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = codeService.updateById(code);
        return ResultUtils.success(result);
    }

}
